package com.shycloud.mido.music.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.music.domain.MisMusicCategory;
import com.shycloud.mido.music.mapper.MisMusicCategoryMapper;
import com.shycloud.mido.music.mapper.MisMusicCollectionMapper;
import com.shycloud.mido.music.mapper.MisMusicLibraryMapper;
import com.shycloud.mido.music.mapper.MisMusicMapper;
import com.shycloud.mido.music.service.MisMusicCategoryService;
import com.shycloud.mido.music.util.CommonString;
import com.shycloud.mido.music.vo.MisMusicCategoryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 曲库一级分类 Controller
 *
 * @author nianhua.jiang
 * @date 2020/4/28
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/musicCate")
@Api(tags = "曲库一级分类模块")
@ApiIgnore
public class MusicCateController {

	/** 曲库一级分类 Service */
	private final MisMusicCategoryService misMusicCategoryService;
	/** 曲库一级分类 mapper */
	private final MisMusicCategoryMapper misMusicCategoryMapper;
	/** 曲库模块 mapper */
	private final MisMusicLibraryMapper misMusicLibraryMapper;
	/** 曲集模块 mapper */
	private final MisMusicCollectionMapper misMusicCollectionMapper;
	/** 曲目模块 mapper */
	private final MisMusicMapper misMusicMapper;
	/** redis 缓存工具类 */
	private final RedisTemplate redisTemplate;

	/**
	 * 新增一级曲库分类
	 *
	 * @param misMusicCategory
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/4/29 14:09
	 */
	@PostMapping("/saveMusicCate")
	@ApiOperation(value = "新增一级曲库分类")
	public R saveMusicCate(@RequestBody MisMusicCategoryVO misMusicCategory) {

		//商城分类
		if ("2".equals(misMusicCategory.getType())) {

		}

		if ("1".equals(misMusicCategory.getType()) || misMusicCategory.getType() == null) {
			//查看是否已经有此分类名
			MisMusicCategory category = misMusicCategoryMapper.selectOne(
					new QueryWrapper<MisMusicCategory>()
							.eq(MisMusicCategory.NAME, misMusicCategory.getName()));

			if (category != null) {
				return new R(CommonConstants.FAIL, "该分类已存在!", false);
			}

			MisMusicCategory entity = new MisMusicCategory();
			BeanUtils.copyProperties(misMusicCategory, entity);
			StringBuffer specialStatus = new StringBuffer();
			List<String> statusList = misMusicCategory.getShowStatus();
			if (statusList != null) {
				for (int i = 0; i < statusList.size(); i++) {
					specialStatus.append(statusList.get(i).equals("1") ? "1" : "0");
				}
				entity.setSpecialStatus(specialStatus.toString());
				entity.setIsSpecial(misMusicCategory.getIsSpecial());

				log.info("entity: " + JSONObject.toJSONString(entity));
			}

			if (misMusicCategoryService.save(entity)) {
				//删除redis的key
				Set musicLibrary = redisTemplate.keys("musicCategoryMobile*");
				if (!musicLibrary.isEmpty()) {
					redisTemplate.delete(musicLibrary);
				}
			}
			return new R(true);
		}
		return new R(false);
	}

	/**
	 * 获取曲库分类
	 *
	 * @param
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/4/22 13:27
	 */
	@GetMapping("/getMusicCategory")
	@ApiOperation(value = "获取曲库分类")
	public R getMusicCategory() {

		QueryWrapper<MisMusicCategory> queryWrapper = new QueryWrapper<>();
		//筛选没有删除的数据
		queryWrapper.eq(MisMusicCategory.DEL_FLAG, CommonString.DELETE_FLG);

		List<MisMusicCategory> misMusicCategories = misMusicCategoryService.getBaseMapper()
				.selectList(queryWrapper);

		List<MisMusicCategoryVO> misMusicCategoriesVO = new ArrayList<>(misMusicCategories.size());

		//遍历曲目分类获取各个分类下曲目数量
		for (MisMusicCategory misMusicCategory : misMusicCategories) {
			MisMusicCategoryVO misMusicCategoryVO = new MisMusicCategoryVO();
			BeanUtils.copyProperties(misMusicCategory, misMusicCategoryVO);

			if (misMusicCategory.getId().equals(23)) {
				misMusicCategoryVO.setMusicCount(null);
			} else {
				//获取曲目数量
				Integer musicCount = misMusicCategoryMapper.getMusicCount(misMusicCategory.getId());
				misMusicCategoryVO.setMusicCount(musicCount);
			}
			misMusicCategoriesVO.add(misMusicCategoryVO);
		}
		//返回结果
		return new R(misMusicCategoriesVO);
	}

	/**
	 * 获取曲库分类 - 小程序专用
	 *
	 * @param
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/4/22 13:27
	 */
	@GetMapping("/getMusicCategoryMini")
	@ApiOperation(value = "获取曲库分类", tags = "课件整合相关接口")
	public R getMusicCategoryMini() {

		QueryWrapper<MisMusicCategory> queryWrapper = new QueryWrapper<>();
		//筛选没有删除的数据
		queryWrapper.eq(MisMusicCategory.DEL_FLAG, CommonString.DELETE_FLG);
		//筛选启用的数据
		queryWrapper.eq(MisMusicCategory.STATUS, "0").orderByAsc(MisMusicCategory.SORT);

		List<MisMusicCategory> misMusicCategories = misMusicCategoryService.getBaseMapper()
				.selectList(queryWrapper);

		//筛选掉全部/推荐的分类
		List<MisMusicCategory> collect = misMusicCategories.stream()
				.filter(x -> !"1".equals(x.getIsSpecial()) && !"全部".equals(x.getName()))
				.collect(Collectors.toList());

		//返回结果
		return new R(collect);
	}

	@GetMapping("/getSpecialCategory")
	@ApiOperation(value = "获取特殊运营分类")
	public R getSpecialOperationMusicCategory() {

		QueryWrapper<MisMusicCategory> queryWrapper = new QueryWrapper<>();
		//筛选没有删除的数据
		queryWrapper.eq(MisMusicCategory.DEL_FLAG, CommonString.DELETE_FLG);
		//queryWrapper.eq(MisMusicCategory.IS_SPECIAL, CommonString.YES);

		List<MisMusicCategory> misMusicCategories = misMusicCategoryService.getBaseMapper()
				.selectList(queryWrapper);

		List<MisMusicCategoryVO> returnList = new ArrayList();
		for (int i = 0; i < misMusicCategories.size(); i++) {
			MisMusicCategory entity = misMusicCategories.get(i);
			MisMusicCategoryVO returnVO = new MisMusicCategoryVO();
			BeanUtils.copyProperties(entity, returnVO);

			List<String> showStatus = new ArrayList<>();
			String status = entity.getSpecialStatus();
			char[] statusArr = status.toCharArray();
			for (int j = 0; j < statusArr.length; j++) {
				if (statusArr[j] == '1') {
					showStatus.add(String.valueOf(j));
				}
			}

			returnVO.setShowStatus(showStatus);
			returnList.add(returnVO);
		}
		//返回结果
		return new R(returnList);
	}

	/**
	 * 获取曲库分类
	 *
	 * @param
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/4/22 13:27
	 */
	@GetMapping("/getMusicCategoryMobile")
	@ApiOperation(value = "获取曲库分类(移动端)")
	@Cacheable(value = "musicCategoryMobile", key = "'musicCategoryMobile_'+#flg")
	public R getMusicCategoryMobile(String flg) {

		QueryWrapper<MisMusicCategory> queryWrapper = new QueryWrapper<>();
		//筛选没有删除的数据
		queryWrapper.eq(MisMusicCategory.DEL_FLAG, CommonString.DELETE_FLG);
		//筛选启用的数据
		queryWrapper.eq(MisMusicCategory.STATUS, "0").orderByAsc(MisMusicCategory.SORT);

		List<MisMusicCategory> misMusicCategories = misMusicCategoryService.getBaseMapper()
				.selectList(queryWrapper);

		List<MisMusicCategoryVO> misMusicCategoriesVO = new ArrayList<>(
				misMusicCategories.size() + 1);

		//遍历曲目分类获取各个分类下曲目数量
		for (MisMusicCategory misMusicCategory : misMusicCategories) {

			MisMusicCategoryVO misMusicCategoryVO = new MisMusicCategoryVO();
			BeanUtils.copyProperties(misMusicCategory, misMusicCategoryVO);
			//获取曲目数量
			Integer musicCount = misMusicCategoryMapper.getMusicCount(misMusicCategory.getId());
			misMusicCategoryVO.setMusicCount(musicCount);
			misMusicCategoriesVO.add(misMusicCategoryVO);
		}

		// 2021/02/22 变更：所有用户都可以看见【定制曲集】标签，【定制曲集】改为【定制专区】
		if (!"1".equals(flg)) {

			MisMusicCategoryVO misMusicCategory = new MisMusicCategoryVO();
			misMusicCategory.setId(6);
			misMusicCategory.setName("定制专区");
			misMusicCategory.setMusicCount(null);
			misMusicCategoriesVO.add(misMusicCategory);

		} else {
			List<MisMusicCategory> collect = misMusicCategoriesVO.stream()
					.filter(x -> !"1".equals(x.getIsSpecial())).collect(Collectors.toList());
			return new R(collect);
		}

		//返回结果
		return new R(misMusicCategoriesVO);
	}

	/**
	 * 获取曲库分类
	 *
	 * @param
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/4/22 13:27
	 */
	@GetMapping("/getMusicCategoryMobileV2")
	@ApiOperation(value = "获取曲库分类(移动端)")
	@Cacheable(value = "musicCategoryMobile", key = "'musicCategoryMobileV2_'+#flg")
	public R getMusicCategoryMobileV2(String flg) {

		QueryWrapper<MisMusicCategory> queryWrapper = new QueryWrapper<>();
		//筛选没有删除的数据
		queryWrapper.eq(MisMusicCategory.DEL_FLAG, CommonString.DELETE_FLG);
		//筛选启用的数据
		queryWrapper.eq(MisMusicCategory.STATUS, "0").orderByAsc(MisMusicCategory.SORT);

		List<MisMusicCategory> misMusicCategories = misMusicCategoryService.getBaseMapper()
				.selectList(queryWrapper);

		List<MisMusicCategoryVO> misMusicCategoriesVO = new ArrayList<>(
				misMusicCategories.size() + 1);

		//遍历曲目分类获取各个分类下曲目数量
		for (MisMusicCategory misMusicCategory : misMusicCategories) {

			if (misMusicCategoriesVO.size() == 1 && !"1".equals(flg)) {
				MisMusicCategoryVO misMusicCategory2 = new MisMusicCategoryVO();
				misMusicCategory2.setId(7);
				misMusicCategory2.setName("我的书架");
				misMusicCategory2.setMusicCount(null);
				misMusicCategoriesVO.add(misMusicCategory2);
			}

			MisMusicCategoryVO misMusicCategoryVO = new MisMusicCategoryVO();
			BeanUtils.copyProperties(misMusicCategory, misMusicCategoryVO);
			//获取曲目数量
			Integer musicCount = misMusicCategoryMapper.getMusicCount(misMusicCategory.getId());
			misMusicCategoryVO.setMusicCount(musicCount);
			misMusicCategoriesVO.add(misMusicCategoryVO);
		}

		// 2021/02/22 变更：所有用户都可以看见【定制曲集】标签，【定制曲集】改为【定制专区】
		if (!"1".equals(flg)) {

			MisMusicCategoryVO misMusicCategory = new MisMusicCategoryVO();
			misMusicCategory.setId(6);
			misMusicCategory.setName("定制专区");
			misMusicCategory.setMusicCount(null);
			misMusicCategoriesVO.add(misMusicCategory);

		} else {
			List<MisMusicCategory> collect = misMusicCategoriesVO.stream()
					.filter(x -> !"1".equals(x.getIsSpecial())).collect(Collectors.toList());
			return new R(collect);
		}

		//返回结果
		return new R(misMusicCategoriesVO);
	}

	@GetMapping("/getNumber")
	@ApiOperation("获取数量统计")
	public R getNumber() {
		Integer cateNum = 0;
		Integer libNum = 0;
		Integer collectNum = 0;
		Integer musicNum = 0;
		QueryWrapper queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("del_flag", 0);
		cateNum = misMusicCategoryMapper.selectList(queryWrapper).size();
		libNum = misMusicLibraryMapper.selectList(queryWrapper).size();
		collectNum = misMusicCollectionMapper.selectList(queryWrapper).size();
		musicNum = misMusicMapper.selectList(queryWrapper).size();
		Map result = new HashMap<>();
		result.put("cateNum", cateNum);
		result.put("libNum", libNum);
		result.put("collectNum", collectNum);
		result.put("musicNum", musicNum);
		return new R(result);
	}

	@GetMapping("/getCateIdByName")
	@ApiOperation("获取曲库详情(编辑用)")
	public R getDetail(String nameListStr) {
		String[] nameList = nameListStr.split(",");
		return new R(misMusicCategoryMapper.getCateIdByName(nameList));
	}

	@PostMapping("/updateMusicCate")
	@ApiOperation("修改曲库分类")
	public R updateMusicCate(@RequestBody MisMusicCategory misMusicCategory) {
		return new R(misMusicCategoryService.updateById(misMusicCategory));
	}

	/**
	 * 删除曲目分类
	 *
	 * @param id 曲库分类 ID
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/4/27 17:14
	 */
	@GetMapping("/delMusicCate")
	@ApiOperation(value = "删除一级曲库分类")
	public R delMusicCate(Integer id) {

		//根据ID查询【曲目分类】
		MisMusicCategory misMusicCategory = misMusicCategoryService.getById(id);
		//逻辑删除，设置为【已删除】
		misMusicCategory.setDelFlag(CommonString.DELETE_FLG_DEL);
		//返回执行结果
		return new R<>(misMusicCategoryService.updateById(misMusicCategory));
	}

	/**
	 * 根据分类名查询分类信息，用于判断分类名称是否重复
	 *
	 * @param name 分类名称
	 * @return com.shycloud.mido.common.core.util.R
	 * @author nianhua.jiang
	 * @date 2020/4/29 14:00
	 */
	@GetMapping("searchMusicCateName")
	@ApiOperation(value = "根据分类名查询分类信息，用于判断分类名称是否重复")
	public R searchMusicCateName(String name) {

		//判断分类名是否重复
		QueryWrapper<MisMusicCategory> queryWrapper = new QueryWrapper<>();
		//将分类名作为条件进行查询
		queryWrapper.eq(MisMusicCategory.NAME, name);
		//存在该分类名
		if (misMusicCategoryService.getBaseMapper().selectList(queryWrapper).size() > 0) {
			//返回错误信息
			return new R(CommonConstants.FAIL, "该分类名已经存在，请重新输入", false);
		}
		return new R(true);
	}

	/**
	 * 开启/禁用分类
	 */
	@PostMapping("triggerCategory")
	@ApiOperation(value = "开启/禁用分类")
	public R disableCategory(@RequestBody String paramsJson) {
		JSONObject paramsJSONObject = JSONObject.parseObject(paramsJson);
		Integer categoryId = paramsJSONObject.getInteger("categoryId");
		String status = paramsJSONObject.getString("status");
		MisMusicCategory entity = new MisMusicCategory();
		entity.setId(categoryId);
		entity.setStatus(status);
		int updateResult = misMusicCategoryMapper.updateById(entity);
		return updateResult == 1 ?
				new R(true) : new R(CommonConstants.FAIL, "开启/禁用分类失败", false);
	}

	/**
	 * 删除分类
	 */
	@PostMapping("deleteCategory")
	@ApiOperation(value = "彻底删除分类")
	public R deleteCategory(@RequestBody String paramsJson) throws Exception {
		JSONObject paramsJSONObject = JSONObject.parseObject(paramsJson);
		Integer categoryId = paramsJSONObject.getInteger("categoryId");

		misMusicCategoryService.deleteCategoryById(categoryId);

		//如果上一步操作抛出异常，会被GlobalExceptionHandler捕获然后抛出错误信息，所以不用担心这里返回true
		return new R(true);
	}

	/**
	 * 编辑分类信息
	 */
	@PostMapping("editCategory")
	@ApiOperation(value = "编辑分类信息")
	public R editCategoryInfo(@RequestBody MisMusicCategoryVO misMusicCategory) throws Exception {
		Integer categoryId = misMusicCategory.getId();
		String name = misMusicCategory.getName();
		Integer sort = misMusicCategory.getSort();
		List<String> statusList = misMusicCategory.getShowStatus();
		StringBuffer specialStatus = new StringBuffer();
		for (int i = 0; i < statusList.size(); i++) {
			specialStatus.append(statusList.get(i).equals("1") ? "1" : "0");
		}

		MisMusicCategory entity = new MisMusicCategory();
		entity.setId(categoryId);
		entity.setName(name);
		entity.setSort(sort);
		entity.setSpecialStatus(specialStatus.toString());
		boolean updateResult = misMusicCategoryService.updateById(entity);

		return updateResult == true ?
				new R(true) : new R(CommonConstants.FAIL, "编辑分类失败", false);
	}

	/**
	 * 获取分类信息
	 */
	@GetMapping("getCategoryInfo")
	@ApiOperation(value = "获取分类信息")
	public R getCategoryInfo(String categoryId) throws Exception {
		QueryWrapper<MisMusicCategory> queryWrapper = new QueryWrapper<>();
		//筛选没有删除的数据
		queryWrapper.eq(MisMusicCategory.DEL_FLAG, CommonString.DELETE_FLG);
		queryWrapper.eq(MisMusicCategory.IS_SPECIAL, CommonString.YES);
		queryWrapper.eq(MisMusicCategory.ID, categoryId);

		MisMusicCategory entity = misMusicCategoryService.getBaseMapper().selectOne(queryWrapper);

		MisMusicCategoryVO returnVO = new MisMusicCategoryVO();
		BeanUtils.copyProperties(entity, returnVO);

		List<String> showStatus = new ArrayList<>();
		String status = entity.getSpecialStatus();
		char[] statusArr = status.toCharArray();
		for (int j = 0; j < statusArr.length; j++) {
			if (statusArr[j] == '1') {
				showStatus.add(String.valueOf(j));
			}
		}

		returnVO.setShowStatus(showStatus);

		return new R(returnVO);
	}

}
